package com.cloud.weixin.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cloud.common.core.asserts.ApiAssert;
import com.cloud.common.core.enums.ErrorCodeEnum;
import com.cloud.common.core.model.response.ApiResponses;
import com.cloud.common.core.model.supers.SuperController;
import com.cloud.common.security.annotation.PreAuth;
import com.cloud.weixin.project.model.entity.WxUser;
import com.cloud.weixin.project.model.parm.WxUserPARM;
import com.cloud.weixin.project.service.IWxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.Set;

/**
 * <p>
 * 微信用户 前端控制器
 * </p>
 *
 * @author Sam
 * @since 2021-04-26
 */
@Api(tags = {"微信用户"})
@RestController
@RequestMapping("/wxUser")
public class WxUserRestController extends SuperController {

    @Autowired
    private IWxUserService wxUserService;

    @PreAuth
    @ApiOperation("查询所有微信用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cursor", value = "当前页数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "nickName", value = "微信用户名称 模糊", paramType = "query"),
            @ApiImplicitParam(name = "tagId", value = "标签id", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "微信用户状态", type = "int", paramType = "query"),
    })
    @GetMapping
    public ApiResponses<IPage<WxUser>> page(@RequestParam(value = "nickName", required = false) String nickName,
                                            @RequestParam(value = "tagId", required = false) String tagId,
                                            @RequestParam(value = "status", required = false) Integer status) {
        LambdaQueryWrapper<WxUser> wrapper = Wrappers.<WxUser>lambdaQuery()
                .like(StringUtils.isNotBlank(nickName), WxUser::getNickName, nickName)
                .eq(Objects.nonNull(status), WxUser::getStatus, status);
        if (StringUtils.isNotBlank(tagId)) {
            wrapper.and(w -> w
                    .eq(WxUser::getTagIdList, "[" + tagId + "]")
                    .or()
                    .like(WxUser::getTagIdList, "," + tagId + ",")
                    .or()
                    .likeRight(WxUser::getTagIdList, "[" + tagId + ",")
                    .or()
                    .likeLeft(WxUser::getTagIdList, "," + tagId + "]"));
        }
        IPage<WxUser> wxUserIPage = wxUserService.page(this.getPage(), wrapper);
        return success(wxUserIPage);
    }

    @PreAuth
    @ApiOperation("单条查询微信用户")
    @GetMapping("/{id}")
    public ApiResponses<WxUser> getById(@PathVariable("id") String id) {
        WxUser wxUser = wxUserService.getById(id);
        return success(wxUser);
    }

    @PreAuth
    @ApiOperation("修改微信用户状态")
    @PutMapping("/changeStatus")
    public ApiResponses<Void> changeStatus(@RequestBody @Validated(WxUserPARM.ChangeStatus.class) WxUserPARM wxUserPARM) {
        WxUser wxUser = new WxUser();
        wxUser.setId(wxUserPARM.getId());
        wxUser.setStatus(wxUserPARM.getStatus());
        ApiAssert.isTrue(ErrorCodeEnum.BAD_UPDATE_FAILURE, wxUserService.updateById(wxUser));
        return success();
    }

    @PreAuth
    @ApiOperation("同步用户")
    @PostMapping("/sync")
    public ApiResponses<Void> sync() {
        try {
            wxUserService.sync();
        } catch (WxErrorException e) {
            ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("同步微信用户失败，请检查参数/配置信息"), e);
        }
        return success();
    }

    @PreAuth
    @ApiOperation("修改微信用户备注")
    @PutMapping("/updateRemark")
    public ApiResponses<Void> remark(@RequestBody WxUserPARM wxUserPARM) {
        wxUserService.updateRemark(wxUserPARM.getId(), wxUserPARM.getRemark());
        return success();
    }

    @PreAuth
    @ApiOperation("打标签")
    @PostMapping("/tagging")
    public ApiResponses<Void> tagging(@RequestBody WxUserPARM wxUserPARM) {
        try {
            String taggingType = wxUserPARM.getTaggingType();
            Set<String> openIdSet = wxUserPARM.getOpenIdSet();
            Set<Long> tagIdSet = wxUserPARM.getTagIdSet();
            for (Long tagId : tagIdSet) {
                wxUserService.tagging(taggingType, tagId, openIdSet);
            }
        } catch (WxErrorException e) {
            ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("打标签失败，请检查参数/配置信息"), e);
        }
        return success();
    }

}

